package com.xhh.nphm.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.poi.ExcelUtil;
import com.xhh.nphm.system.domain.MmailGetDealEty;
import com.xhh.nphm.system.domain.MmailWorkForm;
import com.xhh.nphm.system.domain.TtelGetDealEty;
import com.xhh.nphm.system.domain.TworkFormBaseEty;
import com.xhh.nphm.system.service.*;
import com.xhh.nphm.system.service.impl.WorkFormBaseServiceImpl;
import com.xhh.nphm.web.controller.common.CommonController;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/lookup")
public class LookupController extends BaseController {

    private final String prefix = "system/lookup";

    @Autowired
    private ILookupService lookupService;

    @Autowired
    private CommonController commonController;

    @Autowired
    private MmailWorkFormService mmailWorkFormService;

    @Autowired
    private IMailGetDealService mailGetDealService;

    @Autowired
    private ITelGetDealService telGetDealService;
    @Autowired
    private WorkFormBaseServiceImpl workFormBaseService;

    @Autowired
    private MWorkcsbaseService mWorkcsbaseService;

    @Autowired
    private ITagService tagService;

    /**
     * 查询来电工单列表
     *
     * @param tworkFormBaseEty
     * @return
     */
    @RequestMapping("telWFList")
    public TableDataInfo telWFList(TworkFormBaseEty tworkFormBaseEty) {
        startPage();
        List<TworkFormBaseEty> list = lookupService.telWFList(tworkFormBaseEty);
        return getDataTable(list);
    }

    /**
     * 查询来电工单页面
     *
     * @return
     */
    @GetMapping("/telWFAll")
    public ModelAndView telWFAll() {
        return new ModelAndView(prefix + "/telWFAll");
    }

    /**
     * 查询来信工单页面
     *
     * @return
     */
    @GetMapping("/mailWFAll")
    public ModelAndView mailWFAll() {
        return new ModelAndView(prefix + "/mailWFAll");
    }


    /**
     * 信件工单未回复页面
     *
     * @return
     */
    @GetMapping("/mailWFNotReplyAllWllz")
    public ModelAndView mailWFNotReplyAllWllz() {
        return new ModelAndView(prefix + "/mailWFNotReplyAllWllz");
    }

    /**
     * 信件工单已回复页面
     *
     * @return
     */
    @GetMapping("/mailWFRepliedAllWllz")
    public ModelAndView mailWFRepliedAllWllz() {
        return new ModelAndView(prefix + "/mailWFRepliedAllWllz");
    }


    /**
     * 查询信件工单未回复M列表数据
     *
     * @param mailWorkForm 查询条件
     * @return 列表数据
     */
    @RequestMapping("/mailWFNotReplyAllWllzJson")
    public TableDataInfo mailWFNotReplyAllWllzJson(MmailWorkForm mailWorkForm) {
        startPage();
        List<Map> list = mmailWorkFormService.mailWFNotReplyAllWllzJson(mailWorkForm,getSysUser().getDeptId().toString());
        return getDataTable(list);
    }

    /**
     * 查询信件详情
     * @param mailId
     * @return
     */
    @PostMapping("/mail/{mailId}")
    public Object getMmailGetDealById(@PathVariable Integer mailId) {
        MmailGetDealEty mmailGetDeal = mailGetDealService.getById(mailId);
        if(mmailGetDeal == null) {
            mmailGetDeal = new MmailGetDealEty();
        }
        return mmailGetDeal;
    }

    /**
     * 查询信件工单已回复M列表数据
     *
     * @param mailWorkForm 查询条件
     * @return 列表数据
     */
    @RequestMapping("/mailWFRepliedAllWllzJson")
    public TableDataInfo mailWFRepliedAllWllzJson(MmailWorkForm mailWorkForm) {
        startPage();
        List<Map> list = mmailWorkFormService.mailWFRepliedAllWllzJson(mailWorkForm,getSysUser().getDeptId().toString());
        return getDataTable(list);
    }

    /**
     * 查询来信工单列表
     *
     * @param mmailWorkForm
     * @return
     */
    @RequestMapping("mailWFList")
    @RequestBody
    public TableDataInfo mailWFList(MmailWorkForm mmailWorkForm) {
        startPage();
        List<MmailWorkForm> list = new ArrayList<>();
        if (mmailWorkForm != null && mmailWorkForm.getCdnOper().size() > 0) {
            QueryWrapper<MmailWorkForm> queryWrapper = new QueryWrapper<>();
            List<String> cdnCnts = mmailWorkForm.getCdnCnt();
            List<String> cdnFields = mmailWorkForm.getCdnField();
            List<String> cdnKeys = mmailWorkForm.getCdnKey();
            List<Integer> cdnOpers = mmailWorkForm.getCdnOper();
            String sql = "";
            for (int i = 0; i < cdnOpers.size(); i++) {
                if (StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                    switch (cdnOpers.get(i)) {
                        // 包含  like
                        case 201:
                            for (int j = 0; j < 1; j++) {
                                sql += cdnFields.get(i) + " like " + "'%" + cdnKeys.get(i) + "%'";
                                if (cdnKeys.size() >= 2 && StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                                    if (i != cdnOpers.size() - 1) {
                                        sql += " " + cdnCnts.get(j) + " ";
                                    }
                                }
                            }
                            break;
                        // 等于  =
                        case 101:
                            for (int j = 0; j < 1; j++) {
                                sql += cdnFields.get(i) + "  = " + "'" + cdnKeys.get(i) + "'";
                                if (cdnKeys.size() >= 2 && StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                                    if (i != cdnOpers.size() - 1) {
                                        sql += " " + cdnCnts.get(j) + " ";
                                    }
                                }
                            }
                            break;
                        // 不等于 !=
                        case 102:
                            for (int j = 0; j < 1; j++) {
                                sql += cdnFields.get(i) + " !=" + "'" + cdnKeys.get(i) + "'";
                                if (cdnKeys.size() >= 2 && StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                                    if (i != cdnOpers.size() - 1) {
                                        sql += " " + cdnCnts.get(j) + " ";
                                    }
                                }
                            }
                            break;
                        //  不包括 not like
                        case 202:
                            for (int j = 0; j < 1; j++) {
                                sql += cdnFields.get(i) + " not like " + "'%" + cdnKeys.get(i) + "%'";
                                if (cdnKeys.size() >= 2 && StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                                    if (i != cdnOpers.size() - 1) {
                                        sql += " " + cdnCnts.get(j) + " ";
                                    }
                                }
                            }
                            break;
                        // 大于 >
                        case 120:
                            for (int j = 0; j < 1; j++) {
                                sql += cdnFields.get(i) + " >" + "'" + cdnKeys.get(i) + "'";
                                if (cdnKeys.size() >= 2 && StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                                    if (i != cdnOpers.size() - 1) {
                                        sql += " " + cdnCnts.get(j) + " ";
                                    }
                                }
                            }
                            break;
                        // 小于 <
                        case 110:
                            for (int j = 0; j < 1; j++) {
                                sql += cdnFields.get(i) + " < " + "'" + cdnKeys.get(i) + "'";
                                if (cdnKeys.size() >= 2 && StringUtils.isNotEmpty(StringUtils.trim(cdnKeys.get(i)))) {
                                    if (i != cdnOpers.size() - 1) {
                                        sql += " " + cdnCnts.get(j) + " ";
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            if (cdnKeys.size() >= 2) {
                if (" and ".equals(sql.substring(sql.length() - 5))) {
                    int i = sql.lastIndexOf(" and ");
                    sql = sql.substring(0, i);
                } else if (" or ".equals(sql.substring(sql.length() - 4))) {
                    int i = sql.lastIndexOf(" or ");
                    sql = sql.substring(0, i);
                }
            }
            queryWrapper.ne("PkId", 0);
            queryWrapper.eq("isDel", 0);
            queryWrapper.orderByDesc("PkId");
            queryWrapper.apply(sql);
            list = mmailWorkFormService.list(queryWrapper);
        } else {
            list = lookupService.mailWFList(mmailWorkForm);
        }
        return getDataTable(list);
    }

    @GetMapping("mailDetail/{pkId}")
    public ModelAndView caseDetail(@PathVariable("pkId") Integer pkId, ModelMap map) {
        MmailWorkForm tworkFormBaseEty = mmailWorkFormService.getById(pkId);
        MmailGetDealEty ttelGetDealEty = mailGetDealService.getById(tworkFormBaseEty.getOriginFK());
        if (tworkFormBaseEty != null) {
            map.put("workFormBase", tworkFormBaseEty);
            map.put("telGetDeal", ttelGetDealEty);
        }
        return new ModelAndView(prefix + "/mailDetail");
    }

    /**
     * 进入通话记录列表页面
     *
     * @return 视图
     */
    @GetMapping("telGetAll")
    public ModelAndView telGetAll() {
        return new ModelAndView(prefix + "/telGetAll");
    }

    /**
     * 加载通话记录列表数据
     *
     * @return 列表数据
     */
    @PostMapping("telGetAllList")
    public TableDataInfo telGetAllList(TtelGetDealEty ttelGetDealEty) {
        startPage();
        List<TtelGetDealEty> list = lookupService.telGetAllList(ttelGetDealEty);
        return getDataTable(list);
    }

    /**
     * 进入通话记录详情页面
     *
     * @return 视图
     */
    @GetMapping("/telGetDetail/{id}")
    public ModelAndView telGetDetail(@PathVariable("id") Integer telId, ModelMap map) {
        TtelGetDealEty ttelGetDealEty = telGetDealService.selectByPkId(telId);
        String operator = "";
        if (StringUtils.isNotEmpty(ttelGetDealEty.getYworkNo())) {
            operator = "[" + ttelGetDealEty.getYworkNo() + "]";
        }
        if (StringUtils.isNotEmpty(ttelGetDealEty.getYworker())) {
            operator += ttelGetDealEty.getYworker();
        }
        map.put("telGetDeal", ttelGetDealEty);
        map.put("operator", operator);
        map.put("problem", telGetDealService.problem(ttelGetDealEty.getFromTelA()));
        map.put("history", telGetDealService.countHistory(ttelGetDealEty.getFromTelA()));
        map.put("noLike", telGetDealService.noLike(ttelGetDealEty.getFromTelA()));
        return new ModelAndView(prefix + "/telGetDetail");
    }

    /**
     * 查询信件工单 查看页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/mailOrderDetail/{pkId}")
    public ModelAndView mailOrderDetail(@PathVariable Integer pkId, ModelMap map) {
        SysUser user = getSysUser();
        MmailWorkForm mmailWorkForm = mmailWorkFormService.getById(pkId);
        MmailGetDealEty mmailGetDeal = mailGetDealService.getById(mmailWorkForm.getOriginFK());
        List<Map<String, Object>> mailExistTags = null;
        if (mmailWorkForm != null) {
            map.put("workFormBase", mmailWorkForm);
            map.put("mmailGetDeal", mmailGetDeal);
            // 查询工单已有标签
            mailExistTags = tagService.selectMailExistTag(mmailWorkForm.getOriginFK(),user.getDeptId().toString(),user.getUserId().toString());
        }
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        return new ModelAndView(prefix + "/mailOrderDetail");
    }

    /**
     *根据工单号查询pkId
     * @param workNo
     * @return
     */
    @PostMapping("/getPKIdByWorkNo/{workNo}")
    public AjaxResult getPKIdByWorkNo(@PathVariable String workNo) {
        AjaxResult result = new AjaxResult();
        MmailWorkForm mmailWorkForm = mmailWorkFormService.getByWorkFormNO(workNo);
        if (mmailWorkForm==null){
            return  null;
        }
        String pkId = mmailWorkForm.getPkId();
        result.put("pkId",pkId);
        return result;
    }

    /**
     * 查询电话工单  查看页面
     * mailTelOrderDetail
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/telOrderDetail/{pkId}")
    public ModelAndView telOrderDetail(@PathVariable Integer pkId, ModelMap map) {
        SysUser user = getSysUser();
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(pkId);
        TtelGetDealEty ttelGetDealEty = telGetDealService.getById(tworkFormBaseEty.getGetDealPk());
        List<Map<String, Object>> telExistTags = null;
        if (tworkFormBaseEty != null) {
            map.put("workFormBase", tworkFormBaseEty);
            map.put("telGetDeal", ttelGetDealEty);
            commonController.hidetTel(user,tworkFormBaseEty);
            telExistTags = tagService.selectTelExistTag(String.valueOf(tworkFormBaseEty.getGetDealPk()),user.getDeptId().toString(),user.getUserId().toString());
        }

        if(telExistTags != null && telExistTags.size() > 0){
            map.put("wfTag",telExistTags);
        }
        return new ModelAndView(prefix + "/telOrderDetail");
    }

    /**
     * @description: 查询同号工单详细数据
     * @Author LiuTao
     * @param  pkId
     * @updateTime 2022/8/10 21:30
     * @return java.lang.Object
     * @throws
     **/
    @GetMapping("/sameTelOrderDetail/{pkId}")
    public Object sameTelOrderDetail(@PathVariable Integer pkId) {
        Map map = new HashMap();
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(pkId);
        TtelGetDealEty ttelGetDealEty = telGetDealService.getById(tworkFormBaseEty.getGetDealPk());
        if (tworkFormBaseEty != null) {
            map.put("workFormBase", tworkFormBaseEty);
            map.put("telGetDeal", ttelGetDealEty);
        }
        return map;
    }

    /**
     * 高级查询页面
     */
    @GetMapping("/highLevelSearch")
    public ModelAndView highLevelSearch() {
        return new ModelAndView(prefix + "/highLevelSearch");
    }

    @GetMapping("/simulacrumList/{wfId}")
    public ModelAndView simulacrumList(@PathVariable("wfId") Integer wfId, ModelMap map) {
        map.put("wfId", wfId);
        return new ModelAndView(prefix + "/simulacrumList");
    }


    /**
     * 根据事发地址 查询 电话工单
     *
     * @param fmAddress
     * @return
     */
    @RequestMapping("/telfmAddressJson")
    public TableDataInfo telfmAddressJson(String fmAddress) {
        startPage();
        List<TworkFormBaseEty> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(fmAddress)) {
            list = workFormBaseService.telfmAddressJson(fmAddress);
        }
        return getDataTable(list);
    }

    /**
     * 根据被诉主体 查询 电话工单
     *
     * @param
     * @return
     */
    @RequestMapping("/telaccSubjectJson")
    public TableDataInfo telaccSubjectJson(String accSubject) {
        startPage();
        List<TworkFormBaseEty> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(accSubject)) {
            list = workFormBaseService.telaccSubjectJson(accSubject);
        }
        return getDataTable(list);
    }

    /**
     * 进入电话抄送件列表 页面
     *
     * @return 视图
     */
    @GetMapping("/telCopy")
    public ModelAndView telCopy() {
        return new ModelAndView(prefix + "/telCopy");
    }

    /**
     * 查询抄送件列表数据
     *
     * @param tworkFormBaseEty 查询条件
     * @return 列表数据
     */
    @RequestMapping("/telCopyList")
    public TableDataInfo telCopyList(TworkFormBaseEty tworkFormBaseEty) {
        startPage();
        List<TworkFormBaseEty> list = lookupService.telCopyList(tworkFormBaseEty, getSysUser().getDeptId());
        if(!"304".equals(getSysUser().getDeptId()) && getSysUser().getDeptId().toString().length()==3 || getSysUser().getDeptId().toString().length()/3==2 || getSysUser().getDeptId().toString().length()/3==3){
            //隐藏电话号码 0不隐藏 5隐藏
            for(TworkFormBaseEty t:list){
                t.setFromTelA(t.getFromTelA().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出查询通话记录列表
     */
    @PostMapping("/exportData")
    @ResponseBody
    public AjaxResult exportData(TtelGetDealEty ttelGetDealEty, String[] twsf) {
        List<TtelGetDealEty> list = new ArrayList<>();
        if (twsf != null) {
            List<String> strings = Arrays.asList(twsf);
            List<Integer> ids = strings.stream().map(Integer::valueOf).collect(Collectors.toList());
            list = telGetDealService.listByIds(ids);
        } else {
            list = telGetDealService.telGetList(ttelGetDealEty);
        }
        ExcelUtil<TtelGetDealEty> util = new ExcelUtil<>(TtelGetDealEty.class);
        return util.exportExcel(list, "查询通话记录");
    }

    /**
     * 事发地址画像 页面
     *
     * @return
     */
    @GetMapping("/telfmAddress")
    public ModelAndView telfmAddress() {
        return new ModelAndView(prefix + "/telfmAddress");
    }

    /**
     * 被诉主题画像 页面
     *
     * @return
     */
    @GetMapping("/telaccSubject")
    public ModelAndView telaccSubject() {
        return new ModelAndView(prefix + "/telaccSubject");
    }

    /**
     * 查询已删除信件工单 查看页面
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/mailOrderDeleteDetail/{pkId}")
    public ModelAndView mailOrderDeleteDetail(@PathVariable Integer pkId, ModelMap map) {
        SysUser user = getSysUser();
        MmailWorkForm mmailWorkForm = mmailWorkFormService.getByPkId(pkId);
        MmailGetDealEty mmailGetDeal = mailGetDealService.selectByMailPkId(mmailWorkForm.getOriginFK());
        List<Map<String, Object>> mailExistTags = null;
        if (mmailWorkForm != null) {
            map.put("workFormBase", mmailWorkForm);
            map.put("mmailGetDeal", mmailGetDeal);
            // 查询工单已有标签
            mailExistTags = tagService.selectMailExistTag(mmailWorkForm.getOriginFK(),user.getDeptId().toString(),user.getUserId().toString());
        }
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        return new ModelAndView(prefix + "/mailOrderDetail");
    }

    /**
     * 进入电话抄送件列表 页面
     *
     * @return 视图
     */
    @GetMapping("/mailCopy")
    public ModelAndView mailCopy() {
        return new ModelAndView(prefix + "/mailCopy");
    }

    /**
     * 查询抄送件列表数据
     *
     * @param mmailWorkForm 查询条件
     * @return 列表数据
     */
    @RequestMapping("/mailCopyList")
    public TableDataInfo mailCopyList(MmailWorkForm mmailWorkForm) {
        startPage();
        List<MmailWorkForm> list = mWorkcsbaseService.mailCopyList(mmailWorkForm, getSysUser().getDeptId());
        if(!"304".equals(getSysUser().getDeptId()) && getSysUser().getDeptId().toString().length()==3 || getSysUser().getDeptId().toString().length()/3==2 || getSysUser().getDeptId().toString().length()/3==3){
            //隐藏电话号码 0不隐藏 5隐藏
            for(MmailWorkForm t : list){
                if(t.getFromTel()!= null)
                    t.setFromTel(t.getFromTel().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
            }
        }
        return getDataTable(list);
    }
}
